package com.hpe.util;

import com.hpe.exception.MybatisException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory factory;
    static {
        String resource="mybatis-config.xml";
        try {
            InputStream inputStream = Resources.getResourceAsStream(resource);
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new MybatisException("读取全局配置文件出错，错误信息为"+e.getMessage());
        }
    }
    public SqlSession getSession(){
        if (factory != null){
            return factory.openSession();
        }
        return null;
    }
}
